<?php

class EpayjdpaywapPayment extends BasePayment {


    function get_payform($order_info) {
        $order_info=$this->get_order_info($order_info);
        
        if(!$order_info){
            return false;
        }
        require_once(ROOT_PATH ."/includes/payments/epayjdpaywap/common/SignUtil.php");

        $payment_jdpay_merchantNum = Conf::get('payment_jdpay_merchantNum');

        $params = array();
        $params["currency"] = 'CNY'; #货币种类
        $params["failCallbackUrl"] = $this->_create_return_url($order_info['order_id']); #支付失败页面跳转路径
        $params["merchantNum"] = $payment_jdpay_merchantNum; #商户号
        $params["merchantRemark"] = ''; #商户备注信息
        $params["notifyUrl"] = $this->_create_notify_url($order_info['order_id']); #异步通知地址
        $params["successCallbackUrl"] = $this->_create_return_url($order_info['order_id']); #支付成功页面跳转路径
        $params["tradeAmount"] = intval(bcmul($order_info['money'],100 ,0)); #商户提供的订单的资金总额，单位：分，大于0。
        $params["tradeDescription"] = $this->_get_subject($order_info); #交易描述
        $params["tradeName"] = $this->_get_subject($order_info); #交易名称
        $params["tradeNum"] = $order_info['order_sn']; #交易流水号
        $params["tradeTime"] = date('Y-m-d H:i:s', time());
        $params["version"] = '1.0';
        
        $member_mod = &m('member');
        $member = $member_mod->get('user_id='.$order_info['buyer_id']);
        if(!empty($member)&&$member['jdpaywap_token']){
            $params["token"] = $member['jdpaywap_token'];
        }else{
            $params["token"] = "";
        }
        
        $sign = SignUtil::sign($params);
        $params["merchantSign"] = $sign;

        $gateway = 'https://m.jdpay.com/wepay/web/pay';
        $sHtml = "<form id='payform'  action='" . $gateway . "' _input_charset='utf-8' method='post'>";
        while (list ($key, $val) = each($params)) {
            $sHtml.= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml . "<script>document.getElementById('payform').submit();</script>";
        echo $sHtml;
        exit;
    }

    function _create_return_url($order_id) {
        if ($order_id) {
            return site_url() . "/returnjdpaywap.php?order_id={$order_id}";
        } else {
            return site_url() . "/returnjdpaywap.php";
        }
    }

    function _create_notify_url($order_id) {
        return site_url() . "/notifyjdpaywap.php";
    }
    

    /**
     *    返回通知结果
     *
     *    @author    Garbin
     *    @param     array $order_info
     *    @param     bool  $strict
     *    @return    array
     */
    function verify_notify() {

        include_once(ROOT_PATH .'/includes/payments/epayjdpaywap/common/DesUtils.php');

        $resp = $_POST['resp'];
        $md5Key = Conf::get('payment_jdpay_md5Key');
        $desKey = Conf::get('payment_jdpay_desKey');
        
        
//        $resp = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjxDSElOQUJBTks+DQogICAg\n
//            PFZFUlNJT04+MS4yLjA8L1ZFUlNJT04+DQogICAgPE1FUkNIQU5UPjIyMzEyNzgxPC9NRVJDSEFO\n
//            VD4NCiAgICA8VEVSTUlOQUw+MDAwMDAwMDE8L1RFUk1JTkFMPg0KICAgIDxEQVRBPkJiQ2NzeVUx\n
//            L3kyMjlIeXZ4RFQ1Rm1SVnVjSFRXUFJqaGhyWmViRW1wTVAvL2xjdW04cjBRdVhGcjZPeDY5NXdN\n
//            dEYwblMwWHhjYVYKOVNoMWdrYU16dVJHQXorcytjOWhYREVnMUFXNVNUY3lRM0c3UTZKdzlBajJM\n
//            V0ZpelQ5cUNRYXVqT1FQT3RPWjIyRWF2RzZzNVJYLwo4c3AzYlJKa3hKNnpDYlQ3ckw0anNJZm9G\n
//            T05BdDBIV1VYUUpiazRBa3NlK1d3emNybU5QUDVzMVcyckRPUnA5Z3cwcVVhVW9DZmdNCk5LSGNY\n
//            Ymx2ZVZlVmNZeHlBMHJrRk9xNnFIV0tybEhqRGdqVWl0dFJZQU9CYlA0TDJDSTVvK3dMQzNpV1Z5\n
//            NmVpTHd2QnNJeWM3amwKU2NhanNaTkgxeDlPbUhUVitXWFA1ejBlejdYb0U1SGJUaDBmckdaeERZ\n
//            U2wwZlQvMnkvUDFpbnlrVUpwQktiVnA3c2w4NVVyZjVTcgpZZGM0VzA0QXdJajI0NnBpOW1KUHU2\n
//            d0w2bG5VV24zdXpjT2xDRUxpWkJ6OTJueXI3anlYeXIzR05Ha0VwdFdudXlYenhXV3AzMW8zCmNm\n
//            MFkwWTMrMGJjbm5BPT08L0RBVEE+DQogICAgPFNJR04+YzhhYTc1NGVmZjQ5MzIyNmYzNzU4NTJk\n
//            MGFmNTlmMmU8L1NJR04+DQo8L0NISU5BQkFOSz4NCg0K";
//        $md5Key = "test";
//        $desKey = "Z8KMT8cT4z5ruu89znxFhRP4DdDBqLUH";
        
        

        if ($resp) {
            $params = $this->xml_to_array(base64_decode($resp));
            $ownSign = $this->generateSign($params, $md5Key);
            if ($params ['SIGN'] [0] == $ownSign) {
		$des = new DesUtils (); // （秘钥向量，混淆向量）
		$decryptArr = $des->decrypt ( $params ['DATA'] [0], $desKey ); // 加密字符串
		$params ['data'] = $decryptArr;
                $data = $this->xml_to_array($decryptArr);
                //验证成功，返回支付所需的订单信息
                $notify_result = array(
                    'out_trade_no' => $data['TRADE']['ID'], #商户订单号
                    'trade_no' => $data['TRADE']['ID'], #交易凭据单号
                    'total_fee' => $data['TRADE']['AMOUNT']/100, #涉及金额
                    'trade_status' => '1',
                );
            } else {
                $notify_result = array(
                    'trade_status' => '0',
                );
            }
        } else {
            $notify_result = array(
                'trade_status' => '0',
            );
        }
        return $notify_result;
    }

    function xml_to_array($xml) {
        $array = (array)(simplexml_load_string($xml));
        foreach ($array as $key => $item) {
            $array[$key] = $this->struct_to_array((array) $item);
        }
        return $array;
    }

    function struct_to_array($item) {
        if (!is_string($item)) {
            $item = (array) $item;
            foreach ($item as $key => $val) {
                $item [$key] = $this->struct_to_array($val);
            }
        }
        return $item;
    }

    function generateSign($data, $md5Key) {
        $sb = $data ['VERSION'] [0] . $data ['MERCHANT'] [0] . $data ['TERMINAL'] [0] . $data ['DATA'] [0] . $md5Key;
        return md5($sb);
    }

    function verify_return() {
        $order_id = intval($_GET['order_id']);
        if($order_id){
            header('Location: index.php?app=buyer_order&act=view&order_id='.$order_id);
        }else{
            header('Location: index.php?app=account_log&act=logall');
        }
    }

}

?>